<!--分类字典管理-->
<template>
  <div id="upmsCategoryDict" class="app-container">
    <el-tabs v-model="listQuery.type" class="common-tabs">
      <el-tab-pane v-for="item in categoryTypes" :key="item.dataDictItemCode" :label="item.dataDictItemName" :name="item.dataDictItemCode" />
    </el-tabs>
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar :show-search="false" @refresh="fetchData" @create="handleCreate" @remove="removeRecord">
          <template slot="rightTool">
            <el-button circle :icon="expandAll?'el-icon-arrow-up':'el-icon-arrow-down'" style="  margin-left: 10px;" @click="expandAll?handleMerge():handleExpand()" />
          </template>
        </table-toolbar>
      </div>
      <el-table
        v-if="isMergeTable"
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        row-key="id"
        height="100%"
        highlight-current-row
        :expand-on-click-node="false"
        :default-expand-all="expandAll"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column label="分类名称" prop="name" min-width="100" />
        <el-table-column label="排序" prop="orders" width="100" />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <button-option icon="el-icon-coin" skin="primary" title="新增下级" @click="handleAddNext(scope.row)" />
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="upmsCategoryDictRules"
          :model="upmsCategoryDictRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="分类名称:" prop="name">
            <el-input v-model="upmsCategoryDictRecord.name" maxlength="20" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="排序:" prop="orders">
            <el-input-number v-model="upmsCategoryDictRecord.orders" placeholder="请输入" style="width:100%" show-word-limit :min="1" :max="9999" maxlength="4" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      expandAll: true,
      isMergeTable: true,
      categoryTypes: [],
      list: [],
      listQuery: {
        type: ''
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      upmsCategoryDictRecord: {},
      upmsCategoryDictRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        orders: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'listQuery.type': function(val) {
      this.listQuery = {
        type: val
      }
      this.fetchData()
    }
  },
  created() {
    this.initConfigType()
  },
  methods: {
    handleMerge() {
      this.isMergeTable = false
      this.expandAll = false
      this.$nextTick(() => {
        this.isMergeTable = true
      })
    },
    handleExpand() {
      this.isMergeTable = false
      this.expandAll = true
      this.$nextTick(() => {
        this.isMergeTable = true
      })
    },
    async initConfigType() {
      const response = await this.$store.dispatch('findDataDictItemByCode', 'dataDictType')
      this.categoryTypes = response
      if (this.categoryTypes.length > 0) {
        this.listQuery.type = this.categoryTypes[0].dataDictItemCode
      }
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.fetchData()
    },
    // 表格自带方法结束

    async fetchData() {
      const response = await this.$store.dispatch('upmsCategoryDictTreeByType', this.listQuery.type)
      this.list = response
    },
    /* 新增*/
    handleCreate() {
      this.upmsCategoryDictRecord = {
        pid: 0,
        type: this.listQuery.type,
        orders: 8888
      }
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增分类字典'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddNext(row) {
      this.upmsCategoryDictRecord = {
        pid: row.id,
        type: this.listQuery.type,
        orders: 8888
      }
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增分类字典'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('upmsCategoryDictSave', this.upmsCategoryDictRecord).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.fetchData()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.upmsCategoryDictRecord = Object.assign({}, row) // copy obj
      delete this.upmsCategoryDictRecord.children
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑分类字典'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.upmsCategoryDictRecord)
          this.$store.dispatch('upmsCategoryDictUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.fetchData()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('upmsCategoryDictRemove', ids).then(response => {
            this.fetchData()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    }

  }
}
</script>
<style lang="scss" >
#upmsCategoryDict{
  .el-tabs__content{
      height: 0px !important;
      padding: 0px !important;
    }
    .el-tabs--border-card{
      border: 0px;
    }
    .tab-container{
      height: 100%;
      overflow-y: auto;
      background: #fff;
      padding: 30px 36px 10px 36px;
    }
}
</style>
